package com.itheima.health.utils;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.itheima.health.common.RedisConst;
import com.itheima.health.pojo.Setmeal;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;
import java.util.List;

/**
*倚窗听喧嚣
*2020/4/15
*$ redis 存取数据工具类
*/
public class RedisUtlis {

    // 存入数据到redis
    public static void saveJsonData(String key, List<Setmeal> values) throws Exception {
        JedisPool jedisPool = new JedisPool();
        //获取jieis连接
            Jedis jedis = jedisPool.getResource();
            // 把传入的对象转换成json字符串
            String jsonData = JSON.toJSONString(values);
        //存入到redis
            jedis.set(RedisConst.SETMEAL_DATA_Setmeal,jsonData);
            //释放资源
            jedis.close();
    }

    // 获取缓存数据
    public static List<Setmeal> getJsonData(String key)  throws Exception{
        JedisPool jedisPool = new JedisPool();
        Jedis jedis = jedisPool.getResource();

            String josn = jedis.get(key);
            // 把字符串转换回集合对象
        try {
            //把数据转换成List
            List<Setmeal> setmeals = JSON.parseObject(josn, new TypeReference<List<Setmeal>>() {});
            jedis.close();
            return setmeals;
        }catch (Exception e){
            e.printStackTrace();
            jedis.close();
            return null;
        }
    }
}
